{extend name="admin@public/basic" /}
{block name="style"}{/block}
<!-- <link rel="stylesheet" href="__STATIC__/css/admin/public.css" media="all"/> -->

{block name="cotent"}
<link rel="stylesheet" href="__STATIC__/css/admin/public.css" media="all"/>
<style>
    .tip{
        color: red;
    }
    .gray-tip {
        font-family: sans-serif !important;
        font-weight: 10 !important;
        margin-top: 5px !important;
        color: #A8A8A8 !important;
    }
    .layui-table td, .layui-table th {
        padding: 9px 4px;
    }
    .newupload{
        width: 100px !important;
        height: 40px !important;
        background: url(__STATIC__/image/admin/nopic.png) no-repeat;
        background-size: 100% 100%;
        border:none;
        overflow: hidden;
        cursor: pointer;
        position: relative;
        text-align: center;
    }
    .newInput{
        width: 80px !important;
    }
    .webuploader-container input {
        width: 100%;
        height: 100%;
    }

    .webuploader-pick {
        width: 100%;
        height: 100%;
        border: 1px solid blue;
    }
    .thumbBox {
        position: relative;
    }
    .thumbBox input{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        cursor: pointer;
    }
</style>
<form id="form" class="layui-form" style="width:80%;">
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">基本信息</li>
            <li>套餐详情</li>
            <li>服务详情</li>
            <li>规格</li>

        </ul>
        <div class="layui-tab-content ">
            <!--基本信息-->
            <div class="layui-tab-item layui-show">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">套餐名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" class="layui-input name" lay-verify="required" value="{$data.name|default=''}" placeholder="请输入套餐名称">
                    </div>
                </div>

                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">图片</label>
                    <div class="layui-col-md3 layui-col-xs5">
                        <input type="hidden" name="image" value="{$data.image|default=''}" />
                        <div class="layui-upload-list thumbBox mag0 magt3">
                            <img class="layui-upload-img thumbImg" src="{$data.image_url|default=''}">
                            <input type="file" name="picture" id="picture" multiple="multiple" onchange="uploadFile('picture')" accept="image/jpg,image/jpeg,image/png" />
                        </div>
                    </div>
                </div>

                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-block">
                        <select name="type" class="type" lay-filter="userGrade">
                            {foreach $type as $k => $v}
                                {if !empty($data)}
                                    <option value="{$k}" {if condition="$data.type == $k"}selected{/if}>{$v}</option>
                                {else}
                                    <option value="{$k}">{$v}</option>
                                {/if}
                            {/foreach}
                        </select>
                    </div>
                </div>

                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block status">
                        {if !empty($data)}
                            <input type="radio" name="status" value="1" title="正常" {if condition="$data.status == 1"}checked{/if}>
                            <input type="radio" name="status" value="2" title="异常" {if condition="$data.status == 2"}checked{/if}>
                        {else}
                            <input type="radio" name="status" value="1" title="正常" checked>
                            <input type="radio" name="status" value="2" title="异常" >
                        {/if}
                    </div>
                </div>

                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">描述</label>
                    <div class="layui-input-block">
                        <textarea name="desc" placeholder="描述" class="layui-textarea desc">{$data.desc|default=''}</textarea>
                    </div>
                </div>


                {if !empty($data)}
                <input type="hidden" class="id" name="id" value="{$data.meal_id|default=''}">
                {/if}
            </div>
            <!--套餐详情-->
            <div class="layui-tab-item">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">套餐详情</label>
                    <div class="layui-input-block">
                        <textarea class="layui-textarea layui-hide" name="meal_content" lay-verify="meal_content" id="meal_content">{$data.meal_detail|default=''}</textarea>
                    </div>
                </div>
            </div>
            <!--服务详情-->
            <div class="layui-tab-item">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">服务详情</label>
                    <div class="layui-input-block">
                        <textarea class="layui-textarea layui-hide" name="server_content" lay-verify="server_content" id="server_content">{$data.service_detail|default=''}</textarea>
                    </div>
                </div>
            </div>
            <!-- 规格 -->
            <div class="layui-tab-item">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">商品规格:</label>
                    <div class="layui-col-md12" style="padding-left: 34px">
                        <button class="layui-btn layui-btn-primary" type="button" onclick="addScale()">添加规格 </button><label class="tip">请先选择商品</label><label class="gray-tip" style="line-height:40px;">推荐尺寸:商品规格图片:140px*140px</label>
                        <table class="layui-table" lay-skin="nob" id="table-head">
                            <thead>
                            <tr id="tr1">
                                <th data-name="norms_pic" >图片</th>
                                <th data-name="norms_name">名称</th>
                                <!--<th data-name="norms_size">尺寸</th>-->
                                <th data-name="norms_stock">库存</th>
                                <th data-name="norms_sales">销量</th>
                                <th data-name="norms_oPrice">原价</th>
                                <th data-name="norms_sPrice">售价</th>
                                <!--<th data-name="norms_yjf">用户返积分</th>-->
                                <!--<th data-name="norms_tjf">推荐人返积分</th>-->
                                <!--<th data-name="norms_pjf">评价返积分</th>-->
                                <th >操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {if !empty($data)}
                                {foreach $data.speci as $k => $v}
                                    <tr id='speci{$k}'>
                                        <input type="hidden" id="id" name="id" value="{$v.id}">
                                        <input type="hidden" id="meal_id" name="meal_id" value="{$v.meal_id}">
                                        <td style='position:relative;overflow:hidden'><input type='hidden' id='data_photo{$k}' name='norms_pic' value="{$v.img}" />
                                            <div id='fileList{$k}' class='uploader-list' style='float:right'></div>
                                            <div id='imgPicker{$k}' style='opacity: 0.0;margin-left: 10px;position:absolute;top:0;left:0;width:100%;height:100%'>选择图片</div>
                                            <img id='img_data{$k}' style='float:left;width:100px;height: 50px;' src='{$v.img_url|default=""}'/></td>
                                        <td><input  value='{$v.name}' name='norms_name' type='text' class='layui-input newInput' /></td>
                                        <td><input  value='{$v.stock}' name='norms_stock' type='text' class='layui-input newInput' /></td>
                                        <td><input  value='{$v.sales}' name='norms_sales' type='text' class='layui-input newInput' /></td>
                                        <td><input  value='{$v.oPrice}' name='norms_oPrice' type='text' class='layui-input newInput' /></td>
                                        <td><input  value='{$v.sPrice}' name='norms_sPrice' type='text' class='layui-input newInput' /></td>
                                        <td><button type='button' class='layui-btn layui-btn-sm' onclick='del_scale(this)'>删除</button></td>
                                    </tr>
                                {/foreach}
                            {/if}
                            </tbody>
                        </table>
                        <label class='tip'></label>
                    </div>
                </div>

            </div>
        </div>
    </div>


    <div class="layui-form-item layui-row layui-col-xs12">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm" lay-submit="" id="addUser">确定</button>
            <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary">取消</button>
        </div>
    </div>
</div>
</form>

{/block}

{block name="script"}
<script type="text/javascript" src="__STATIC__/layuicms/layui/layui.js"></script>
<script type="text/javascript" src="__STATIC__/plugs/webuploader.min.js"></script>

<script>

//若为新增时生成一次规格
$(function(){
    {if empty($data)}addScale();dealPicture();{else/}dealPicture();{/if}
})



layui.use(['form','layer','layedit','upload','element'],function(){
    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        element = layui.element,
        $ = layui.jquery;

    //用于同步编辑器内容到textarea
    layedit.sync(editIndex);
    layedit.sync(editIndex2);

    //一些事件监听
    element.on('tab(demo)', function (data) {
        console.log(data);
    });

    /**
     * 新增以及编辑后台用户
     */
    $("#addUser").click(function () {
        layedit.sync(editIndex);
        layedit.sync(editIndex2);
        var url = '{if empty($data)}{:url("$thisClass/add")}{else/}{:url("$thisClass/edit")}{/if}';

        var data = {
            id: $(".id").val(),
            name: $(".name").val(),
            type: $(".type").val(),
            status: $('input[name="status"]:checked').val(),
            image: $('input[name="image"]').val(),
            desc: $(".desc").val(),
            meal_content: $("#meal_content").val(),
            server_content: $("#server_content").val(),
        };
        // 处理规格信息
        var speci = [];
        var tdnode = $("#tr1").find("th");
        var index = $("#table-head").find("tbody").find("tr").length;
        for(var i=0;i<index;i++){
            var speciOne = {};
            var trData = $("#speci"+i);
            var trId = $("#speci"+i).find("input[name='id']").val();
            var trMealid = $("#speci"+i).find("input[name='meal_id']").val()
            if(trId!='' && trId != undefined && trId !=null){
                speciOne['id'] = trId;
                speciOne['meal_id'] = trMealid;
            }
            for(var j=0;j<tdnode.length-1;j++){
                var tdData = $(trData).find("input[name='"+tdnode[j].dataset.name+"']").val();
                speciOne[tdnode[j].dataset.name] = tdData;
            }
            speci.push(speciOne);
        }
        data['speci']=speci;

        $.ajax({
            url: url,
            method:"POST",
            data: data,
            success:function(res){
                console.log(res);
                if(res.code ==1){
                    layer.msg(res.msg,{icon: 1})
                    setTimeout(function(){
                        //刷新父页面
                        parent.location.reload();
                    },500);

                }else{
                    layer.msg(res.msg);
                }
            }   
        })
        return false;
    });

    
    //创建一个编辑器,套餐详情
    var editIndex = layedit.build('meal_content',{
        height : 535,
        uploadImage : {
            url : "{:url('api/Upload/uploadRichTextFile')}"
        }
    });
    //创建一个编辑器,套餐详情
    var editIndex2 = layedit.build('server_content',{
        height : 535,
        uploadImage : {
            url : "{:url('api/Upload/uploadRichTextFile')}"
        }
    });
    form.render();

})
// 添加规格
function addScale() {
    var tdnode = $("#tr1").find("th");
    console.log(tdnode[0].dataset.name);
    var index = $("#table-head").find("tbody").find("tr").length;
    console.log(index);
    var html='';
    if (tdnode.length-1 > 0) {
        html += "<tr id='speci"+index+"'><td style='position:relative;overflow:hidden'><input type='hidden' id='data_photo" + index + "' name='" + tdnode[0].dataset.name + "' />"
                        +"<div id='fileList" + index + "' class='uploader-list' style='float:right'></div>"
                        +"<div id='imgPicker" + index + "' style='opacity: 0.0;margin-left: 10px;position:absolute;top:0;left:0;width:100%;height:100%'>选择图片</div>"
                        +"<img id='img_data" + index + "' style='float:left;width:100px;height: 50px;' src='__STATIC__/image/admin/nopic.png'/></td>";
   
        for (var i = 1; i < tdnode.length - 1; i++) {
            console.log(tdnode[i].style.display)
            if (tdnode[i].style.display == 'none') {
                continue;
            }
            console.log(tdnode[i].dataset.val);
            if (tdnode[i].dataset.val >= 0) {
                html += "<td><input  value='" + tdnode[i].dataset.val + "' name='" + tdnode[i].dataset.name + "' type='text' class='layui-input newInput' /></td>";
            } else {
                html += "<td><input  value='' name='" + tdnode[i].dataset.name + "' type='text' class='layui-input newInput' /></td>";
            }

        }
        html += "<td><button type='button' class='layui-btn layui-btn-sm' onclick='del_scale(this)'>删除</button></td>";
        html += "</tr>";
        $("#table-head").find("tbody").append(html);
        dealPicture();
    }
    
}
// 删除规格
function del_scale(obj) {
    var tr = obj.parentNode.parentNode;
    var tbody = tr.parentNode;
    var index = $("#table-head").find("tbody").find("tr").length;
    console.log(index);
    if(index>1){
        tbody.removeChild(tr);
    }
    
}

// 上传图片
function uploadFile(inputName){
    var data = new FormData();
    $.each($('input[name="'+inputName+'"]')[0].files, function(i, file) {
        data.append('file', file);

    });
    console.log(data.get(inputName))
    //清空图片
    $('#'+inputName).val('');
    //提交数据
    $.ajax({
        url: "{:url('api/Upload/uploadFile')}",
        type: 'POST',
        data: data,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        // dataType: 'json',
        success: function(res) {
            if (res.code == 1000) {
                $('.thumbImg').attr('src',res.data.all_url);
                $("input[name='image']").val(res.data.url);
            }
        },
        error: function(returndata) {
            parent.layer.msg('数据异常', {
                icon: 2,
                time: 2000
            });
            return false;
        }
    });
}

function dealPicture(){
    var div = $("div[id^=fileList]");
    var uploader;
    div.each(function(index){  

        var $list = $('#fileList' + index);
        //上传图片,初始化WebUploader
        uploader = WebUploader.create({
            auto: true, // 选完文件后，是否自动上传。
            swf: '/static/admin/webupload/Uploader.swf', // swf文件路径
            server: "{:url('api/Upload/uploadFile')}", // 文件接收服务端。
            duplicate: true, // 重复上传图片，true为可重复false为不可重复
            pick: '#imgPicker' + index, // 选择文件的按钮。可选。

            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },
            'onUploadSuccess': function (file, data, response) {
                var src = data.data.all_url;
                var title = data.data.url;
                $("#data_photo" + index).val(title);
                $("#img_data" + index).attr('src', src).show();
            }
        });

        uploader.on('fileQueued', function (file) {

        });

        // 文件上传成功
        uploader.on('uploadSuccess', function (file) {
            //$('#' + file.id).find('p.state').text('上传成功！');
        });

        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function (file) {
            //$('#' + file.id).find('p.state').text('上传出错!');
        });
    }); 
    
}
    
    
</script>
{/block}
